<?php

namespace Frieza\Modules\Circle\Extensions;

use Doraemon\model\Circle\CircleBaseInfo;
use Doraemon\model\Circle\JoinCircle;
use Doraemon\model\Circle\PhotosCircle;
use Doraemon\model\Photos;
use Encore\Admin\Actions\Action;
use Encore\Admin\Facades\Admin;
use Illuminate\Http\Request;
use Doraemon\cache\Circle\CircleContentCounter;
use Doraemon\service\Circle\PhotosCircle as sPhotosCircle;
use Doraemon\model\Circle\PhotosCircle as mPhotosCircle;

class CarryButton extends Action
{
    public  $name = '搬运圈子内容';

    protected  $selector = '.btn-danger';

    public function handle(Request $request): \Encore\Admin\Actions\Response
    {
        $result = $this->check($request->post('note_id'), $request->post('circle_id'));
        if (1 == $result['status']) {
            return $this->response()->success($result['msg'])->refresh();
        }
        return $this->response()->error($result['msg']);
    }

    public function form()
    {
        $circleName = CircleBaseInfo::getNameId();
        $this->text('note_id', 'noteID')->required();
        $this->select('circle_id', '绑定圈子')->options($circleName)->required();
    }

    /**
     * 检验并添加
     *
     * @param $pId
     * @param $cId
     * @return array
     */
    public function check($pId, $cId): array
    {
        $info = Photos::getPhoto($pId);
        if (empty($info)) {
            return ['status' => 0, 'msg' => '输入的 Id 不存在'];
        }
        $isBind = PhotosCircle::getFieldByCondition(['photos_id' => $pId], ['id']);
        if (!empty($isBind)) {
            return ['status' => 0, 'msg' => '该 note 已绑定圈子'];
        }
        $isJoin = JoinCircle::getByUidAndCircleId($info['uid'], $cId);
        if (empty($isJoin)) {
            return ['status' => 2, 'msg' => '当前内容作者还不是成员'];
        }

        //去添加
        $operId = Admin::user()->id;
        $operRemark = '后台操作绑定';

        $result = sPhotosCircle::addPhotoCircle($pId, $cId, mPhotosCircle::JOIN_CHANNEL_ADMIN, $operId, $operRemark);

        if (empty($result)) {
            return ['status' => 3, 'msg' => '绑定失败'];
        }

        //计数器-递增圈子内容总数 $circleId = 圈子id
        CircleContentCounter::incrTotal($cId);
        // 递增圈子每日内容数 $circleId = 圈子id $member 是内容id
        //todo 根据时间戳判断是否增加每日的内容数
        CircleContentCounter::incrCountByDay($cId, $pId);
        return ['status' => 1, 'msg' => '绑定成功'];
    }

    public function html(): string
    {
        return "<a class='report-posts btn btn-sm btn-danger'><i class='fa fa-info-circle'></i> 搬运</a>";
    }
}